package com.msb.juc.c_020;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 这里使用 ReentrantLock完成同样的功能
 * 需要注意的是：一定要手动释放锁
 * 使用 sync锁定，在遇到异常后，JVM会自动释放锁；但是 Lock必须手动释放锁
 */
public class T02_ReentrantLock {

    Lock lock = new ReentrantLock();

    void m1() {
        try {
            // synchronized(this) {}
            lock.lock();
            for (int i = 0; i < 10; i++) {
                TimeUnit.SECONDS.sleep(1);
                System.out.println(i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void m2() {
        try {
            lock.lock();
            System.out.println("m2 ...");
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        T02_ReentrantLock rl = new T02_ReentrantLock();
        new Thread(rl::m1).start();
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(rl::m2).start();
    }
}
